import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/Login.vue";
import Home from "../views/Home.vue";
import Welcome from "../components/Welcome.vue";
import UserList from "../components/users/UserList.vue";
import Roles from "../components/roles/Roles.vue";
import Rights from "../components/rights/Rights.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    component: Login
  },
  {
    path: "/home",
    component: Home,
    children: [
      {
        path: "/",
        redirect: "/welcome"
      },
      {
        path: "/welcome",
        component: Welcome
      },
      {
        path: "/users",
        component: UserList
      },
      {
        path: "/roles",
        component: Roles
      },
      {
        path: "/rights",
        component: Rights
      }
    ]
  }
];

const router = new VueRouter({
  // mode: "history",
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳过来的
  // next 是一个函数 ，表示放行

  // 用户访问的是login页面 ， 直接放行
  if (to.path === "/login") return next();

  // 用户访问home页面时 获取 token 判断是否存在token 若存在则放行
  const tokenStr = window.sessionStorage.getItem("token");
  if (!tokenStr) return next("/login");
  next();
});

export default router;
